import React, {Component} from 'react';
import {Button, Col, Row, Spin} from 'antd';
import '../css/register.css';
import {Back} from '../components/EditComponent';
import {config} from "../config";
import {order, wechat} from "../value";
import app from '../AppMethod';
import moment from 'moment';

class AddOrder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: []
        }
    };

    render() {
        return (
            <div className="orderListContainer">
                <div>
                    <Back title="添加配送订单" back="true" click={() => this.handleBack()}/>
                </div>
                <Spin spinning={this.state.loading}>
                    <div className="orderListContent" style={{paddingBottom: '110px'}}>
                        {
                            this.state.data.length > 0 ?
                                this.state.data.map((item, index) => {
                                    return (
                                        <OrderItem data={item} key={index}/>
                                    )
                                }) : <div style={{textAlign: 'center', marginTop: '40px'}}>无订单数据，请扫一扫添加</div>
                        }
                    </div>
                </Spin>
                <div style={{
                    width: '100%',
                    bottom: '0px',
                    position: 'fixed',
                    backgroundColor: '#fff',
                    paddingBottom: '10px'
                }}>
                    <Button type='primary' style={{width: '96%', marginLeft: '2%', height: '45px', fontSize: '18px'}}
                            onClick={() => this.handleScanQrCode()}>扫一扫</Button>
                    {
                        this.state.data.length > 0 ?
                            <Button type='primary' style={{
                                width: '96%',
                                marginLeft: '2%',
                                height: '45px',
                                fontSize: '18px',
                                marginTop: '10px'
                            }} onClick={() => this.handleDrop('/confirmOrder')}>确定</Button> : ''
                    }
                </div>
            </div>
        )
    };

    componentDidMount() {
        this.handleGetSingPackage();
    }

    /**
     * 处理跳转页面事件
     * @param path
     */
    handleDrop(path) {
        this.props.history.push(config.path + path);
    };

    /**
     * 处理返回页面事件
     */
    handleBack() {
        this.props.history.goBack();
    };

    /**
     * 处理扫码事件（根据扫码结果查询代配送单列表）
     */
    handleScanQrCode() {
        let _this = this;
        window.wx.scanQRCode({
            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
                _this.setState({loading: true});
                var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                let car_no = result.split(',')[1];
                app.setData('car_no', car_no);
                app.post(order.QUERY_OUTPUTBYCARNO, {car_no: car_no}).then((resultData) => {
                    if (resultData.code === 1) {
                        let orderData = resultData.data.dataSet;
                        for (let i = 0; i < orderData.length; i++) {
                            orderData[i].output_order_time = orderData[i].output_order_time === null ? "" : moment(orderData[i].output_order_time).format('YYYY-MM-DD');
                        }
                        _this.setState({data: orderData, loading: false});
                    } else {
                        _this.setState({data: [], loading: false});
                    }
                });
            }
        })
    };

    /**
     * 通过config接口注入权限验证配置（微信公众号）
     * @returns {Promise.<void>}
     */
    async handleGetSingPackage() {
        let result = await app.post(wechat.GET_SIGNPACKAGE, {url: window.location.href.split("#")[0]});
        if (result.code === 1) {
            let data = result.data;
            window.wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.appId, // 必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature,// 必填，签名
                jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表
            });
            window.wx.error(function (res) {
                app.alert(JSON.stringify(res), 'error', 3);
            });
        } else {
            app.alert(result.msg, 'error', 4);
        }
    };
}

/**
 * 订单组件
 */
class OrderItem extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        let {output_num, output_status, output_money, output_need_money, output_real_money, output_follow_name, ouptut_follow_phone, output_order_time, route_name, output_real_package, output_real_parts} = this.props.data;
        let all_s;
        all_s = Number(output_real_package) + Number(output_real_parts);
        let status = Number(output_status);
        let statusText = '';
        switch (status) {
            case 0:
                statusText = '待接单';
                break;
            case 1:
                statusText = '已接单';
                break;
            case 2:
                statusText = '配货中';
                break;
            case 3:
                statusText = '待对货';
                break;
            case 4:
                statusText = '待配送';
                break;
            case 5:
                statusText = '待改单';
                break;
            case 6:
                statusText = '配送中';
                break;
            case 7:
                statusText = '已完成';
                break;
        }
        if (output_money == null || output_money == undefined) {
            output_money = 0;
        }
        if (output_real_money == null || output_real_money == undefined) {
            output_real_money = 0;
        }
        if (output_need_money == null || output_need_money == undefined) {
            output_need_money = 0;
        }
        return (
            <Row className="allContainer">
                <Row className="orderItem">
                    <Col className="orderItemNumber" xs={24} md={8} lg={6}>订单号：{output_num}</Col>
                    <Col className="orderPerson" xs={12} md={8} lg={6}>订单状态：{statusText}</Col>
                    <Col className="orderNotPay" xs={12} md={8} lg={6}>订单金额：{output_money}元</Col>
                    <Col className="orderNotPay" xs={12} md={8} lg={6}>应收款金额：{output_need_money}元</Col>
                    <Col className="orderIsPay" xs={12} md={8} lg={6}>已收款金额：{output_real_money}元</Col>
                    <Col className="orderPerson" xs={24} md={8} lg={6}>跟单人：{output_follow_name}</Col>
                    <Col className="orderPerson" xs={24} md={8} lg={6}>跟单人联系电话：{ouptut_follow_phone}</Col>
                    <Col className="orderPerson" xs={24} md={24} lg={24}>下单日期：{output_order_time}</Col>
                    <Col className="orderPerson" xs={24} md={24} lg={24}>路线名称：{route_name}</Col>
                    <Col className="orderPerson" xs={8} md={8} lg={8}>件数：{output_real_package}</Col>
                    <Col className="orderPerson" xs={8} md={8} lg={8}>散件数：{output_real_parts}</Col>
                    <Col className="orderPerson" xs={8} md={8} lg={8}>总件数：{all_s}</Col>
                </Row>
            </Row>
        )
    }
}

export default AddOrder;